<!-- 租户管理页面 -->
<template>
  <div class="tenant-index">
    <!-- <span
      class="foldBtn"
      :class="isFold ? 'foldBtn_fold' : ''"
      @click="foldBtnClick"
      >{{ isFold ? ">>" : "&lt;&lt;" }}</span
    > -->
    <i
      class="foldBtn"
      :class="
        isFold ? 'el-icon-d-arrow-right foldBtn_fold' : 'el-icon-d-arrow-left'
      "
      @click="foldBtnClick"
    ></i>
    <div class="domain" :class="isFold ? 'domain_fold' : ''">
      <div class="domainInputBox">
        <el-input
          placeholder="输入关键字进行过滤"
          size="mini"
          v-model="domainKeyword"
          style="margin-bottom: 10px"
          @change="filterKeyWord"
        >
          <i slot="prefix" class="el-input__icon el-icon-search"></i>
        </el-input>
      </div>

      <el-tree
        class="filter-tree"
        :data="domainList"
        :props="defaultProps"
        default-expand-all
        :filter-node-method="filterNode"
        :highlight-current="true"
        @node-click="domainNodeClick"
        ref="tree"
      >
      </el-tree>
    </div>
    <div
      class="tenant"
      :class="isFold ? 'tenant_expand' : ''"
      v-loading="loading"
    >
      <div class="domain-header" :class="isFold ? 'domain-header_expand ' : ''">
        <div class="domain-sear" v-if="isShowSear">
          <el-form size="mini" inline class="form_header">
            <el-form-item label="关键字">
              <el-input
                placeholder="关键字检索(名称/授权标识)"
                v-model="searParams.keyword"
              ></el-input>
            </el-form-item>
            <el-form-item label="创建人">
              <el-select
                v-model="searParams.createBy"
                size="mini"
                clearable
                placeholder="请选择"
              >
                <el-option
                  v-for="item in createTenantList"
                  :key="item.id"
                  :label="item.username"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间">
              <el-date-picker
                v-model="createDate"
                style="width: 300px"
                size="mini"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                align="center"
                value-format="yyyy-MM-dd HH:mm:ss"
                @change="handleSelectDate"
              >
              </el-date-picker>
            </el-form-item>
            <el-button size="mini" type="primary" @click="searchBtnClick"
              >查询</el-button
            >
            <el-button size="mini" @click="resetBtnClick('tenantTable')"
              >重置</el-button
            >
          </el-form>
        </div>
        <div>
          <div class="domain-bottomBtn">
            <div>
              <el-button
                type="primary"
                size="mini"
                plain
                icon="el-icon-plus"
                class="addBtn"
                @click="addTenantBtnClick"
                >新增</el-button
              >
              <el-button
                type="danger"
                size="mini"
                plain
                icon="el-icon-delete"
                @click="delBtnClick"
              >
                删除</el-button
              >
            </div>

            <div class="tenant-oper-right">
              <el-button
                icon="el-icon-search"
                size="mini"
                circle
                @click="isShowSear = !isShowSear"
              ></el-button>
              <el-button
                icon="el-icon-refresh"
                size="mini"
                circle
                @click="list()"
              ></el-button>
            </div>
          </div>
        </div>
        <!-- <div class="tenant-oper">
          <span class="tenant-oper-left">
            <el-button
              type="primary"
              size="mini"
              plain
              icon="el-icon-plus"
              v-if="innerMenu.add.flag"
              >新增</el-button
            >
            <el-button
              type="success"
              size="mini"
              plain
              icon="el-icon-edit"
              v-if="innerMenu.upd.flag"
              >修改</el-button
            >
            <el-button
              type="danger"
              size="mini"
              plain
              icon="el-icon-delete"
              v-if="innerMenu.del.flag"
            >
              删除</el-button
            >
          </span>
          <div class="tenant-oper-right">
            <el-button
              icon="el-icon-search"
              size="mini"
              circle
              @click="isShowSear = !isShowSear"
            ></el-button>
            <el-button
              icon="el-icon-refresh"
              size="mini"
              circle
              @click="list()"
            ></el-button>
          </div>
        </div> -->
      </div>

      <el-table
        :data="tenantPage.list"
        style="width: 100%"
        @selection-change="tableSelectChange"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column prop="username" label="用户名"> </el-table-column>
        <el-table-column prop="nickname" label="昵称"> </el-table-column>
        <el-table-column prop="phone" label="手机号码"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="idCard" label="身份证"> </el-table-column>
        <el-table-column fixed="right" label="操作" width="120">
          <template slot-scope="scoped">
            <el-link
              type="primary"
              class="alterLink"
              @click="alterLinkClick(scoped.row)"
              >修改</el-link
            >
            <el-link type="primary" @click="delLinkClick(scoped.row.id)"
              >删除</el-link
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="page"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="tenantPage.totalCount"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="tenantPage.pageSize"
        @current-change="handleModifyOffset"
        @size-change="handleModifyLimit"
      >
      </el-pagination>
    </div>
    <tenant-form
      :alterFormData="alterFormData"
      :drawerName="drawerName"
      :currentDomainId="currentDomainId"
      @alterDrawerClose="alterDrawerClose"
      @createTenantEvent="createTenantEvent"
      @alterTenantEvent="alterTenantEvent"
    />
  </div>
</template>

<script>
import tenantForm from "./cpns/TenantForm.vue";

import { getCacheInnerMenu } from "@/utils/menu";

import { createTenant, alterTenant, delTenantById } from "@/api/tenant";

export default {
  watch: {
    // searParams(val) {
    //   this.$refs.tree.filter(val);
    // },
    "searParams.keyword"(val) {
      if (val === "") {
        this.searParams.domainId = this.currentDomainId;
        this.list();
        return;
      }
    },
    "searParams.createBy"(val) {
      if (val === "") {
        this.searParams.domainId = this.currentDomainId;
        this.list();
        return;
      }
    },
    createDate(val) {
      if (val === null) {
        this.searParams.domainId = this.currentDomainId;
        this.list();
        return;
      }
    },
    domainKeyword(val) {
      if (val === "") {
        this.getDomains();
      }
    },
  },
  components: {
    tenantForm,
  },
  data() {
    return {
      domainKeyword: "",
      tenantList: [],
      createDate: [],
      isShowSear: true,
      loading: false,
      isFold: false,
      alterFormData: {},
      drawerName: "",
      currentDomainId: "",
      currentSelectId: [],
      searParams: {},
      createTenantList: [],
      createDate: [],
      domainList: [],
      tempDomainList: [],
      filterText: "",
      defaultProps: {
        children: "children",
        label: "name",
      },
      tenantPage: [],
      innerMenu: {},
    };
  },
  created() {
    this.resetSearParams();
    this.getDomains();
    this.list();
    this.innerMenu = getCacheInnerMenu(this.$route.meta.id);
    console.log(this.innerMenu);
  },
  mounted() {},
  methods: {
    /**
     * 重置检索菜单
     */
    resetSearParams() {
      this.searParams = {
        offset: 1,
        limit: 5,
        keyword: "",
        domainId: "",
      };
    },
    /**
     * 重置搜索参数
     */
    handleResetSearParams() {
      this.resetSearParams();
    },
    /**
     * 页码改变
     */
    handleModifyOffset(offset) {
      this.searParams.offset = offset;
      this.list();
    },
    /**
     * 页数改变
     */
    handleModifyLimit(limit) {
      this.searParams.limit = limit;
      this.list();
    },
    /**
     * 查询租户列表
     */
    list() {
      this.loading = true;
      this.$store.dispatch("tenant/listInAuth", this.searParams).then((res) => {
        console.log(res);
        if (res.code === 0) {
          if (res.data.list.length) {
            this.tenantPage = res.data;
            this.createTenantList = res.data.list.map((item) => {
              return { username: item.username, id: item.id };
            });
          } else {
            this.tenantPage = res.data;
          }
        }
        this.loading = false;
      });
    },
    /**
     * 过滤区域
     */
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    /**
     * 选择时间
     */
    handleSelectDate() {},
    /**
     * 获取区域列表
     */
    getDomains() {
      this.$store.dispatch("domain/list", this.searParams).then((res) => {
        if (res.code === 0) {
          this.domainList = res.data;
          this.tempDomainList = res.data;
        }
      });
    },
    // domain节点点击事件
    domainNodeClick(data) {
      if (!this.currentDomainId) {
        this.currentDomainId = data.id;
      } else {
        if (this.currentDomainId === data.id) return;
        this.currentDomainId = data.id;
      }
      this.searParams.domainId = this.currentDomainId;
      this.list();
    },
    // 折叠按钮点击
    foldBtnClick() {
      this.isFold = !this.isFold;
    },
    // 新增按钮点击事件
    addTenantBtnClick() {
      this.drawerName = "add";
    },
    // 修改链接点击事件
    async alterLinkClick(row) {
      console.log(row);
      this.alterFormData = {
        id: row.id,
        nickname: row.nickname,
        wechat: row.wechat,
        phone: row.phone,
        email: row.email,
        idCard: row.idCard,
        level: row.level,
        remark: row.remark,
        type: -1,
        domainId: this.currentDomainId,
      };
      this.drawerName = "alter";
    },
    async createTenantEvent(formData) {
      console.log(formData);
      const data = await createTenant(formData);
      console.log(data);
      if (data.code === 0 && data.data) {
        this.$message({
          message: "添加租户成功",
          type: "success",
        });
        this.searParams.domainId = formData.domainId;
        this.list();
        this.drawerName = "";
      }
    },
    async alterTenantEvent(formData) {
      console.log(formData);
      const data = await alterTenant(formData);
      console.log(data);
      if (data.code === 0 && data.data) {
        this.$message({
          message: "修改租户成功",
          type: "success",
        });
        this.searParams.domainId = formData.domainId;
        this.list();
        this.drawerName = "";
      }
    },
    alterDrawerClose() {
      this.drawerName = "";
      this.alterFormData = {};
    },
    tableSelectChange(selection) {
      this.currentSelectId = selection.map((item) => item.id);
    },
    delLinkClick(id) {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const data = await delTenantById({
            tenantIds: id instanceof Array ? id : [id],
          });
          console.log(data);
          if (data.code === 0 && data.data === true) {
            this.searParams.domainId = this.currentDomainId;
            this.list();
            this.$message({
              message: "删除租户成功",
              type: "success",
            });
          } else {
            this.$message.error("删除租户失败");
          }
        })
        .catch(() => {});
    },
    delBtnClick() {
      if (this.currentSelectId.length === 0) {
        this.$message({
          message: "请选择需要删除的租户",
          type: "warning",
        });
      } else {
        this.delLinkClick(this.currentSelectId);
      }
    },
    searchBtnClick() {
      console.log(this.searParams);
      this.searParams.fromTime = this.createDate[0];
      this.searParams.toTime = this.createDate[1];
      this.list();
    },
    resetBtnClick() {
      this.searParams = {};
    },
    filterKeyWord(value) {
      if (value === "") return;
      this.domainList = [];
      this.recursionDomains(value, this.tempDomainList);
    },
    recursionDomains(value, data) {
      data.forEach((item) => {
        console.log(item.name);
        if (item.name.search(value) !== -1) {
          console.log(item.name.search(value !== -1));
          console.log(item);
          this.domainList.push(item);
        }
        if (item.children.length !== 0) {
          this.recursionDomains(value, item.children);
        }
      });
    },
  },
};
</script>
<style scoped>
/* @import url(); 引入css类 */
.tenant-index {
  position: relative;
  height: 100vh;
  margin: 1%;
  /* margin-top: 0;
  margin-left: 0; */
  display: flex;
  background: #fff;
  overflow: hidden;
}

.addBtn {
  height: 28px;
}

.form_header {
  margin-right: 20px;
}

.domain-header {
  position: relative;
  left: -35px;
  width: calc(100vw - 377px);
  padding-top: 15px;
  padding-left: 35px;
  border-top: 1px solid #ebedf0;
  border-bottom: 1px solid #ebedf0;
  transition: width 0.2s ease;
}

.domain-header_expand {
  width: calc(100vw - 107px);
  transition: width 0.2s ease;
}

.domain {
  position: absolute;
  left: 0;
  flex: 0.15;
  width: 270px;
  height: 100vh;
  background: #fff;
  padding: 15px 40px 0 10px;
  transition: left 0.2s ease;
}

.domain_fold {
  left: -270px;
  transition: left 0.2s ease;
}

.domain-sear {
  display: flex;
  justify-content: space-between;
}

.domain-bottomBtn {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.domainInputBox {
  position: relative;
  left: -10px;
  width: 270px;
  padding: 15px 40px 0 10px;
  border-top: 1px solid #ebedf0;
}

.tenant {
  position: absolute;
  left: 270px;
  flex: 0.8;
  /* margin-left: 15px; */
  padding-left: 35px;
  /* width: 1542px; */
  width: calc(100vw - 377px);
  height: 100vh;
  background: #fff;
  border-left: 1px solid #ebedf0;
  padding-top: 15px;
  transition: all 0.2s ease;
}

.tenant_expand {
  left: 0;
  width: calc(100vw - 107px);
  transition: all 0.2s ease;
}

.page {
  text-align: center;
  margin-top: 15px;
}

.tenant-oper {
  display: inline-block;
  margin: 0 0 12px 0;
  /* display: flex;
  align-items: center;
  justify-content: space-between; */
}

.tenant-oper-right {
  margin-right: 20px;
}

.foldBtn {
  display: inline-block;
  position: absolute;
  top: 30px;
  left: 251px;
  width: 20px;
  height: 28px;
  line-height: 28px;
  background: #fff;
  /* color: black; */
  border: 1px solid #ebedf0;
  border-right: none;
  border-radius: 2px;
  z-index: 9;
  cursor: pointer;
  transition: left 0.2s ease;
}

.foldBtn_fold {
  left: 1px;
  border: 1px solid #ebedf0;
  border-left: none;
  transition: left 0.2s ease;
}

.alterLink {
  margin-right: 20px;
}
</style>
